#include <stdio.h>
#include "Apiapr.h"

void InitAprPool()
{
	apr_pool_initialize();
}

void FreeAprPool()
{
	apr_pool_terminate();
}

int InitSessionPool(myevent_s *ev, unsigned long lSession_Memory_size)  
{
	int fd = ev->fd;
	apr_allocator_t *session_allocator;
	if(APR_SUCCESS != apr_allocator_create(&session_allocator))
	{
		printf("ALLOCATOR: failure! pid[%d]: fd[%d]: from [%s:%u]\n", getpid(), fd, ev->rIp, ev->rPort);
		return -1;
	}

	apr_allocator_max_free_set(session_allocator, lSession_Memory_size);

	apr_pool_t *session_pool;
	if(APR_SUCCESS != apr_pool_create_ex(&session_pool, NULL, NULL, session_allocator))
	{
		apr_allocator_destroy(session_allocator);
		session_allocator = NULL;
		printf("POOL: failure! pid[%d]: fd[%d]: from [%s:%u]\n", getpid(), fd, ev->rIp, ev->rPort);
		return -1;
	}

	ev->pSession_pool = session_pool;
	ev->frame.maxsize = 0;//flag new require, assign when require begin
	printf("POOL: ok! pid[%d]: fd[%d]: from [%s:%u]\n", getpid(), fd, ev->rIp, ev->rPort);

	return 0;
}

int FreeSessionPool(myevent_s *ev)  
{
	apr_pool_destroy(ev->pSession_pool);
	apr_allocator_destroy(apr_pool_allocator_get(ev->pSession_pool));
}

void InitRequireFrame(myevent_s* ev, unsigned long lRequire_Memory_size)
{
	if(ev->frame.maxsize == 0)
	{
		apr_pool_t *require_pool;
		apr_pool_create(&require_pool, ev->pSession_pool);
		ev->pRequire_pool = require_pool;
		ev->frame.pBuf = apr_palloc(require_pool, lRequire_Memory_size);
		ev->frame.maxsize = lRequire_Memory_size;
		ev->frame.curPos = 0;
		memset(ev->frame.pBuf, 0x00, lRequire_Memory_size); // fot test		
	}
}

void FreeRequireFrame(myevent_s* ev)
{
	apr_pool_destroy(ev->pRequire_pool);
	ev->pRequire_pool = NULL;
	ev->frame.pBuf = NULL;
	ev->frame.maxsize = 0;
	ev->frame.curPos = 0;
}
